<template>
  <div class="document-upload">
    <el-card shadow="never" class="header-card">
      <template #header>
        <div class="card-header">
          <el-icon><Upload /></el-icon>
          <span>上传文档</span>
        </div>
      </template>
      <el-text type="info">将工单、故障分析、设备说明书等文档上传到知识库</el-text>
    </el-card>

    <el-tabs v-model="activeTab" class="upload-tabs">
      <!-- 单文件上传 -->
      <el-tab-pane label="单文件上传" name="single">
        <el-card shadow="never" class="upload-card">
          <!-- 拖拽上传区域 -->
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :on-change="handleFileSelect"
            :show-file-list="false"
            drag
            accept=".txt,.pdf,.md,.doc,.docx"
            class="upload-dragger"
          >
            <el-icon class="el-icon--upload"><Upload /></el-icon>
            <div class="el-upload__text">
              拖拽文件到此处或 <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持 .txt, .pdf, .md, .doc, .docx 格式文件
              </div>
            </template>
          </el-upload>

          <!-- 文档信息表单 -->
          <el-card v-if="selectedFile" shadow="never" class="form-card">
            <template #header>
              <el-text>文档信息</el-text>
            </template>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="文件名">
                <el-text>{{ selectedFile.name }}</el-text>
              </el-descriptions-item>
            </el-descriptions>

            <el-form :model="uploadForm" label-width="100px" class="upload-form-fields">
              <el-form-item label="文档类型" required>
                <el-select v-model="uploadForm.doc_type" placeholder="选择文档类型" style="width: 100%">
                  <el-option label="工单" value="workorder" />
                  <el-option label="故障分析" value="fault_analysis" />
                  <el-option label="设备说明书" value="equipment_manual" />
                  <el-option label="其他" value="other" />
                </el-select>
              </el-form-item>

              <el-form-item label="文档来源" required>
                <el-input v-model="uploadForm.source" placeholder="如：工单系统、故障库等" />
              </el-form-item>

              <el-form-item label="标签">
                <el-input v-model="uploadForm.tags" placeholder="用逗号分隔多个标签" />
              </el-form-item>

              <el-form-item label="优先级">
                <el-select v-model="uploadForm.priority" placeholder="选择优先级" style="width: 100%">
                  <el-option label="低" value="low" />
                  <el-option label="中" value="medium" />
                  <el-option label="高" value="high" />
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-space>
                  <el-button type="primary" @click="submitUpload" :loading="uploading">上传文档</el-button>
                  <el-button @click="resetForm">取消</el-button>
                </el-space>
              </el-form-item>
            </el-form>
          </el-card>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 上传进度 -->
    <el-card v-if="uploadProgress > 0 && uploadProgress < 100" shadow="never" class="progress-card">
      <el-progress :percentage="uploadProgress" :format="format" />
    </el-card>

    <!-- 上传历史 -->
    <el-card v-if="uploadHistory.length > 0" shadow="never" class="history-card">
      <template #header>
        <div class="card-header">
          <el-icon><Clock /></el-icon>
          <span>最近上传</span>
        </div>
      </template>
      <el-table :data="uploadHistory" stripe style="width: 100%">
        <el-table-column prop="filename" label="文件名" min-width="200" show-overflow-tooltip />
        <el-table-column prop="type" label="类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeColor(row.type)">{{ getTypeLabel(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.status === 'success'" type="success">成功</el-tag>
            <el-tag v-else-if="row.status === 'error'" type="danger">失败</el-tag>
            <el-tag v-else type="info">上传中</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="time" label="时间" width="180" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Upload, Clock } from '@element-plus/icons-vue'
import { useKnowledgeBaseStore } from '@/stores/knowledge-base'

const kbStore = useKnowledgeBaseStore()

const activeTab = ref('single')
const selectedFile = ref(null)
const uploading = ref(false)
const uploadProgress = ref(0)
const uploadHistory = ref([])

const uploadForm = ref({
  doc_type: '',
  source: '',
  tags: '',
  priority: 'medium'
})

const uploadRef = ref(null)

const typeMap = {
  workorder: '工单',
  fault_analysis: '故障分析',
  equipment_manual: '设备说明书',
  other: '其他'
}

const typeColorMap = {
  workorder: 'info',
  fault_analysis: 'warning',
  equipment_manual: 'success',
  other: 'default'
}

const getTypeLabel = (type) => {
  return typeMap[type] || type
}

const getTypeColor = (type) => {
  return typeColorMap[type] || 'default'
}

const handleFileSelect = (file) => {
  selectedFile.value = file.raw || file
}

const submitUpload = async () => {
  if (!uploadForm.value.doc_type || !uploadForm.value.source) {
    ElMessage.error('请填写文档类型和来源')
    return
  }

  uploading.value = true
  uploadProgress.value = 0

  try {
    const metadata = {
      tags: uploadForm.value.tags.split(',').filter(t => t.trim()),
      priority: uploadForm.value.priority
    }

    await kbStore.uploadFile(
      selectedFile.value, 
      uploadForm.value.doc_type, 
      metadata,
      uploadForm.value.source
    )

    uploadProgress.value = 100
    ElMessage.success('文档上传成功！')

    // 添加到历史
    uploadHistory.value.unshift({
      filename: selectedFile.value.name,
      type: uploadForm.value.doc_type,
      status: 'success',
      time: new Date().toLocaleString()
    })

    // 重置表单
    resetForm()
    setTimeout(() => {
      uploadProgress.value = 0
    }, 2000)
  } catch (err) {
    uploadProgress.value = 0
    ElMessage.error('文档上传失败: ' + err.message)
    uploadHistory.value.unshift({
      filename: selectedFile.value.name,
      type: uploadForm.value.doc_type,
      status: 'error',
      time: new Date().toLocaleString()
    })
  } finally {
    uploading.value = false
  }
}

const resetForm = () => {
  selectedFile.value = null
  uploadForm.value = {
    doc_type: '',
    source: '',
    tags: '',
    priority: 'medium'
  }
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

const format = (percentage) => {
  return `${percentage}%`
}
</script>

<style scoped>
.document-upload {
  padding: 0;
}

.header-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.upload-tabs {
  margin-bottom: 20px;
}

.upload-card {
  margin-bottom: 20px;
}

.upload-dragger {
  width: 100%;
}

.form-card {
  margin-top: 20px;
}

.upload-form-fields {
  margin-top: 20px;
}

.progress-card {
  margin-top: 20px;
}

.history-card {
  margin-top: 20px;
}

.history-card :deep(.el-table) {
  background: transparent;
}

.history-card :deep(.el-table__header) {
  background: var(--el-bg-color-page);
}

@media (max-width: 768px) {
  .upload-form-fields {
    margin-top: 15px;
  }

  .history-card :deep(.el-table) {
    font-size: 12px;
  }
}
</style>












